<?php
namespace app\console\controller;
use app\console\model\Role as SelfModel;
use app\console\model\Privilege as PrivilegeModel;
use app\console\model\RolePri as RolePriModel;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;


class Role extends Base
{


    public function index()
    {

        $data = SelfModel::alias('role')
            ->join('role_pri','role.id = role_pri.role_id','LEFT')
            ->join('privilege','role_pri.pri_id = privilege.id','LEFT')
            ->field('role.*,GROUP_CONCAT(pri_name) pri_name')
            ->group('role.id')
            ->paginate(10)->each(function ($item,$key){
                $item->pri_name = strLength($item->pri_name,80);
            });

        return View::fetch('', ['data' => $data]);
    }

    public function create()
    {

        if ($this->request->isPost()) {
            $inquire = $this->request->param();
            $ret = (new SelfModel())->save($inquire);
            if ($ret) {
                win('操作成功', Route::buildUrl('index'));
            }
            win('操作失败');
        }
        $list = getMenuTree(PrivilegeModel::order(['sort' => 'asc','id' => 'asc'])->where('status',1)->select());//where('status',1)->
        return View::fetch('',['list' => $list]);
    }


    public function update()
    {
        $param = $this->request->param();
        $id = input('id');
        $info = SelfModel::find($id);
        if ($this->request->isPost()) {
            $ret = $info->save($param, $id);
            if ($ret !== false) {

                win('修改成功', Route::buildUrl('index'));
            }
            fail('修改失败');
        }

        $list = getMenuTree(PrivilegeModel::order(['sort' => 'asc','id' => 'asc'])->where('status',1)->select());//where('status',1)->
        $rpData = RolePriModel::field('GROUP_CONCAT(pri_id) pri_id')->where(['role_id' => $id])->find();
        return View::fetch('create', ['info' => $info,'list' => $list,'list1' => $rpData['pri_id']]);
    }

    public function destory($id)
    {
        if ($this->request->isGet()) {
            $ret = SelfModel::destroy($id);
            if ($ret){
                jump('删除成功', Route::buildUrl('index'));
            }
            fail('删除失败');
        }
    }

    public function check()
    {
        $inquire = $this->request->param();
        $ret = SelfModel::where('id', $inquire['id'])->value($inquire['check']) == '1' ? 2 : 1;
        if (SelfModel::where('id', $inquire['id'])->update([$inquire['check'] => $ret])) {
            return $ret;
        }
        return false;
    }

}